package com.burgeon.backend.SHOPBACKEND.service.Impl;

import com.burgeon.backend.SHOPBACKEND.entity.IndexCoupon;
import com.burgeon.backend.SHOPBACKEND.mappers.BackendIndexCouponMapper;
import com.burgeon.backend.SHOPBACKEND.service.BackendIndexCouponService;
import com.burgeon.backend.entity.CouponType;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.mappers.CouponMapper;
import com.burgeon.backend.service.ex.ErrorDataException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BackendIndexCouponServiceImpl implements BackendIndexCouponService {
    @Autowired
    private BackendIndexCouponMapper backendIndexCouponMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private CouponMapper couponMapper;
    //查看首页优惠卷
    @Override
    public List<IndexCoupon> findIndexCoupon(String account) {
        String token = accountMapper.GetTokenForAccount(account);//获取token

        List<IndexCoupon> indexCoupons = backendIndexCouponMapper.findIndexCoupon(token);
        for (IndexCoupon indexCoupon: indexCoupons) {
            if (null != indexCoupon.getTid()) {


                CouponType couponType = couponMapper.findCouponTypeById(indexCoupon.getTid());
                indexCoupon.setName(couponType.getName());
                indexCoupon.setOriginal(couponType.getOriginal());
                indexCoupon.setPrice(couponType.getMoney());
            }
        }
        return indexCoupons;
    }

    //新增首页优惠卷
    @Override
    public Integer addIndexCoupon(IndexCoupon indexCoupon,String account) {
        String token = accountMapper.GetTokenForAccount(account);//获取token
        indexCoupon.setToken(token);
        try {
           return  backendIndexCouponMapper.addIndexCoupon(indexCoupon);
        }catch (Exception e){
            e.printStackTrace();
            throw new ErrorDataException("新增首页优惠卷错误");
        }

    }

    //根据id删除首页优惠卷
    @Override
    public Integer deleteIndexCoupon(String id) {
        try {
            return backendIndexCouponMapper.deleteIndexCoupon(id);
        }catch (Exception e){
            e.printStackTrace();
            throw new ErrorDataException("删除优惠卷错误");
        }
    }
}
